#include "tj_form_recipe_check.h"
#include "ui_tj_form_recipe_check.h"

#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QSqlError>
#include <QTimer>
#include <synchapi.h>
#include <QSqlRecord>

tj_form_recipe_check::tj_form_recipe_check(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::tj_form_recipe_check)
{
    ui->setupUi(this);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/form_recipe_check").toRect();
    this->setGeometry(rct);

    terminalCode = setIni.value("cfdy/terminal").toString();    //当前工作窗口代码

//    QString undrug_list_ini = setIni.value("cfdy/undrug_dept").toString();    //需要输出的非药品窗口
//    QStringList undrug_list = undrug_list_ini.split("^");

//    undrug_dept = "'undrug_dept'";

//    foreach (QString s, undrug_list)
//    {
//        undrug_dept += ",'" + s + "'";
//    }




    ui->de_recipe_date->setDate(QDate::currentDate());

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);

    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);


    md_recipe_list = new QSqlQueryModel();
    md_recipe_content = new QSqlQueryModel();

    //准备工作终端列表
    qro->exec("select t_name, t_code , dept_code from pha_sto_terminal where t_type = '0'");
    while(qro->next())
    {
        ui->cbb_terminal->addItem(qro->value(0).toString());
        if( qro->value(1).toString() == terminalCode )
        {
            terminalName = qro->value(0).toString();    //当前窗口代码对应的名称
            deptCode = qro->value(2).toString();    //
        }
    }

    //网络参数
    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    sq = "create temporary table if not exists "
         "tmp_recipe_check ("
         "item_code VARCHAR(12) not null unique , " //项目编码
            "item_name VARCHAR(100) not null,"  //项目名称
            "qty_r decimal(6) not null," //处方数量
            "qty_w decimal(6) not null," //窗口数量
            "qty_unit VARCHAR(10) not null,"   //数量单位
            "specs varchar(30),"    //规格
            "rec_sn decimal(20),"  //fin_opb_feedetail.mo_order
            "bar_code_base varchar(20),"    //溯源码包含的药品识别码
            "bar_code varchar(40),"    //溯源码等
            "sequence_no int "  //处方内药品序号
            ")";

    qDebug()<<"建立临时表 tmp_recipe_check："<<sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "无法新建处方校验临时表 tmp_recipe_check ！\n" + qrm->lastError().text());
        return;
    }

    sq = "create temporary table if not exists "
         "tmp_recipe_code_list ("
         "item_code VARCHAR(12) not null , " //项目编码
            "bar_code varchar(30) not null unique,"  //条码
            "bar_code_base varchar(20),"    //溯源码包含的药品识别码
            "bar_code_count int,"    //条码出现的次数
            "rec_sn decimal(15)" //等于 fin_opb_feedetail.mo_order 和 met_order_recipedetail.sequence_no';
            ")";

    qDebug()<<"建立临时表 tmp_recipe_code_list："<<sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "无法新建处方校验临时表 tmp_recipe_code_list ！\n" + qrm->lastError().text());
        return;
    }

    //增加临时表索引
    qrm->exec(" alter tmp_recipe_code_list "
              " add unique index prim_key (bar_code, rec_sn)");


    //提示声音
    snd_error.setSource(QUrl("qrc:/snd/error.wav"));
    snd_reci_finish.setSource(QUrl("qrc:/snd/reci_finish.wav"));
    snd_drug_finish.setSource(QUrl("qrc:/snd/drug_finish.wav"));
    //设置音量
    snd_error.setVolume(0.9);
    snd_reci_finish.setVolume(0.9);
    snd_drug_finish.setVolume(0.9);
    //音效设置为单次播放，不循环
    snd_error.setLoopCount(0);
    snd_reci_finish.setLoopCount(0);
    snd_drug_finish.setLoopCount(0);

    //条码录入时限，为兼容扫描器硬件失灵不能送出回车信号
    tm_code_input = new QTimer(this);
    connect(tm_code_input, &QTimer::timeout, this, &tj_form_recipe_check::tm_code_input_timeout);

    ui->pb_fresh_recipe->setFocus();

    is_repair = false ; //处方补录状态
    cur_clinic_code.clear();
    cur_recipe_no.clear();
    cur_card_no.clear();

}

tj_form_recipe_check::~tj_form_recipe_check()
{
    delete ui;
}

void tj_form_recipe_check::tm_code_input_timeout()
{
    tm_code_input->stop();
    if(ui->ck_manual->isChecked())
    {
        //手工录入，忽略计时器超时
        return;
    }
    on_le_code_returnPressed();
}

void tj_form_recipe_check::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/form_recipe_check", QVariant(this->geometry()));


    qro->exec("select t_code from pha_sto_terminal where t_name = '" + ui->cbb_terminal->currentText() + "'");

    if(qro->next())
    {
        terminalCode = qro->value(0).toString();        //科室代码
    }

    setIni.setValue("cfdy/terminal",terminalCode);

    emit destroyW( "form_recipe_check" );

}

void tj_form_recipe_check::on_cbb_terminal_currentTextChanged(const QString &arg1)
{
    qro->exec("select t_code ,dept_code from pha_sto_terminal where t_name = '" + arg1 + "'");

    if(qro->next())
    {
        deptCode = qro->value(1).toString();
        terminalCode = qro->value(0).toString();        //科室代码
        terminalName = arg1;

        qDebug()<<terminalCode<<terminalName;
    }
}

QString tj_form_recipe_check::get_recipe_no(QString no)
{
    //录入的可能是发票号，尝试用发票号检索处方号

    sq = "select recipe_no from pha_sto_recipe"
         " where recipe_no = '" + no + "' "
         " or invoice_no = '" + pub::add0(no, 12) + "' ";
    qrot->exec(sq);

    qDebug() << "检索处方号:";
    qDebug() << sq << "\n";

    QStringList recipe_list;

    while(qrot->next())
    {
        recipe_list << qrot->value(0).toString();
    }

    QString recipe;

    if(recipe_list.size() > 0)
    {
        recipe = recipe_list.join("','") ;
    }
    else
    {
        //输入的即不是发票号，也不是处方号
        recipe = "";
    }

    return recipe;

}

void tj_form_recipe_check::on_le_recipe_no_returnPressed()
{
    //保存当前处方号
    cur_recipe_no = ui->le_recipe_no->text().trimmed();

    if(cur_recipe_no.isEmpty())
    {
        return;
    }

    QString recipe ;

    if(ui->rb_code_check->isChecked())
    {
        //追溯码查询模式

        recipe = get_recipe_no(cur_recipe_no);

        if(recipe.isEmpty())
        {
            QMessageBox::information(this, "注意", "请输入正确的发票号或处方号！");
            return;
        }

        sq = " select bar.oper_date 日期 , bar.bar_code 追溯码 , base.trade_name 药品名称,"
             " reg.card_no 病志号, reg.name 患者姓名, bar.clinic_code"
             " from pha_sto_barcode_rec bar"
             " left join fin_opr_register reg on reg.clinic_code = bar.clinic_code"
             " left join pha_com_baseinfo base on base.id_code = bar.bar_code_base "
             " where bar.recipe_no in ('%1') and bar.valid_state = '1' "
             " order by bar.oper_date";
        sq = sq.arg(recipe);

        qDebug()<<"查询指定发票号或处方号关联的追溯码";
        qDebug()<<sq<<"\n";

        md_recipe_content->setQuery(sq, pub::db_o);

        if(md_recipe_content->rowCount() < 1)
        {
            snd_error.play();
            QMessageBox::information(this, "注意", "找不到指定的处方号或发票号的内容！");
        }
        else
        {
            int w = ui->tv_recipe_content->width();
            ui->tv_recipe_content->setModel(md_recipe_content);
            pub::setColumnWidth(ui->tv_recipe_content, "0.15^0.15^0.15^0.15^0.15^0.15^0^0",w);
        }

        ui->le_code->setFocus();
        ui->le_code->clear();

        return;
    }

    if( ui->rb_code_repair->isChecked())
    {
        recipe = get_recipe_no(cur_recipe_no);

        if(recipe.isEmpty())
        {
            QMessageBox::information(this, "注意", "请输入正确的发票号或处方号！");
            return;
        }

        QMessageBox::StandardButton bt;
        bt = QMessageBox::question(this, "注意", "确认要取消处方号'"+recipe+"'的核验标志？");
        if(bt == QMessageBox::Yes)
        {
            sq = "update sun_recipe_pr set analyzed = '0' where recipe_no in ('"
                    + recipe + "')";
            qDebug()<<"取消处方核验标志:"<<sq;
            qro->exec(sq);

            sq = "delete from pha_sto_barcode_rec where recipe_no in ('"
                    + recipe + "') and valid_state = '2' ";
            qDebug()<<"删除可能已经存在的临时状态条码:"<<sq;
            qro->exec(sq);

            sq = "update pha_sto_barcode_rec set valid_state = '2' where recipe_no in ('"
                    + recipe + "')";
            qDebug()<<"设置已经录入条码为临时状态:"<<sq;
            qro->exec(sq);
        }
        else
        {
            return;
        }

        sq = "select clinic_code from sun_recipe_pr where recipe_no in ('"
                + recipe + "')";
        qDebug()<<"提取处方 clinic code :"<<sq;
        qro->exec(sq);
        qro->next();

        sq = "select reg_date from fin_opr_register where clinic_code = '"
             + qro->value(0).toString() + "'";
        qDebug()<<"提取处方挂号日期 ："<<sq;

        qro->exec(sq);
        qro->next();

        ui->de_recipe_date->setDate(qro->value(0).toDate());

        on_pb_fresh_recipe_clicked();
        return;

    }

    //检查处方是否已经经过核验
    sq = "select * from sun_recipe_pr where analyzed = '1' and recipe_no = '"
            + cur_recipe_no + "'";
    qDebug()<<"检查处方是否已经经过核验:"<<sq;
    qro->exec(sq);

    if(qro->next())
    {
        snd_error.play();

        QMessageBox::information(this, "注意", "处方已经调配完成！");
        ui->le_recipe_no->setFocus();
        ui->le_recipe_no->selectAll();

        return;
    }

    current_status = "recipe_no_return";

    recipe_finished = false;    //开始新处方，设置未完成标志

    //清空旧数据
    qrm->exec("delete from tmp_recipe_code_list");
    qrm->exec("delete from tmp_recipe_check");

    sq = "select fin.item_name , fin.specs , fin.qty/fin.pack_qty qty," // 0 - 2
         "fin.clinic_code, fin.mo_order, fin.card_no, "// 3 - 5
         "fin.price_unit, fin.sequence_no, fin.item_code" // 6 - 8
         " from fin_opb_feedetail fin "
         //" left join pha_com_base base on base.drug_code = fin.item_code "
         " where recipe_no = '" + cur_recipe_no + "'";
    sq += " and cancel_flag = '1' ";
    sq += " order by sequence_no";

    qDebug()<<"提取处方号关联的药品信息："<<sq;

    if(!qro->exec(sq))
    {
        snd_error.play();

        QMessageBox::information(this, "注意", "提取处方号关联的药品信息失败！\n" + qro->lastError().text());
        ui->le_recipe_no->setFocus();
        ui->le_recipe_no->selectAll();

        return;
    }

    while(qro->next())
    {
        cur_card_no =  qro->value("card_no").toString();

        sq = " insert into tmp_recipe_check ("
             "item_code , " //项目编码
                "item_name ,"  //项目名称
                "specs, "//规格
                "qty_r," //处方数量
                "qty_w," //窗口数量
                "qty_unit,"   //数量单位
                "rec_sn,"  //fin_opb_feedetail.mo_order
                "sequence_no" //药品序号
                " )values(";
        sq += "'" + qro->value("item_code").toString() + "',";
        sq += "'" + qro->value("item_name").toString() + "',";
        sq += "'" + qro->value("specs").toString() + "',";
        sq += qro->value("qty").toString() + ", 0, ";
        sq += "'" + qro->value("price_unit").toString() + "',";
        sq += "'" + qro->value("mo_order").toString() + "',";
        sq += qro->value("sequence_no").toString() ;
        sq += ")";

        qDebug()<<"处方项目插入临时表："<<sq;
        if(!qrm->exec(sq))
        {
            snd_error.play();
            QMessageBox::information(this, "注意", "插入临时表发生错误！\n" + qrm->lastError().text());
            return;
        }
    }

    //保存当前患者门诊编号
    qro->first();
    cur_clinic_code = qro->value("clinic_code").toString();


    sq = "select item_name 药品名称, specs 规格, qty_unit 单位, qty_r 处方数量,qty_w 投放数量,"
         " item_code "
         " from tmp_recipe_check order by sequence_no";

    md_recipe_content->setQuery(sq, pub::db_m);

    if(md_recipe_content->rowCount() < 1)
    {
        snd_error.play();

        QMessageBox::information(this, "注意", "找不到处方号关联的药品！");
        ui->le_recipe_no->setFocus();
        ui->le_recipe_no->selectAll();

        return;
    }

    ui->tv_recipe_content->setModel(md_recipe_content);
    int w = ui->tv_recipe_content->width();
    pub::setColumnWidth(ui->tv_recipe_content, "0.35^0.2^0.1^0.15^0.15", w);

    ui->le_code->setFocus();
    ui->le_code->clear();

    snd_reci_finish.play();

    //可能是补录处方，检查已经录入过的条码
    sq = "select bar_code, bar_code_count from pha_sto_barcode_rec"
         " where recipe_no = '"+cur_recipe_no+"' and valid_state = '2'";
    qDebug()<<"可能是补录处方，检查已经录入过的条码";
    qDebug()<<sq<<"\n";
    qrot->exec(sq);

    is_repair = true;  //处方补录状态

    while (qrot->next())
    {
        int count = qrot->value(1).toInt();
        QString code = qrot->value(0).toString();

        if(code == "no_code" || code == "0" || code == "0000000")
        {
            continue;
        }

        for(int i = 0 ; i< count; i++)
        {
            ui->le_code->setText(code);
            //qApp->processEvents();
            on_le_code_returnPressed();
          //  Sleep(50);
        }
    }
    ui->le_code->setFocus();
    ui->le_code->clear();
    current_status = "";
    is_repair = false;  //处方补录状态
}

void tj_form_recipe_check::on_le_code_returnPressed()
{

    //扫码之后，清除补录数量
    ui->le_count->clear();
    //如果当前有扫码延时，停止
    if(tm_code_input->isActive())
    {
        tm_code_input->stop();
    }

    QString code = ui->le_code->text().trimmed();
    QString base_code = "";

    if(code.isEmpty())
    {
        snd_error.play();
        ui->le_code->setFocus();
        ui->le_code->clear();
        return;
    }

    if(code.length() == 6 || code.length() == 13)
    {
        //内部制剂编码或商品码
        base_code = code;
    }
    else if(code.length() == 20 )
    {
        //溯源码
        base_code = code.mid(0, 7);
    }
    else
    {
        snd_error.play();
        QMessageBox::information(this, "注意", "药品识别码长度无效！");
        ui->le_code->setFocus();
        ui->le_code->clear();
        return;
    }

    if(ui->rb_code_check->isChecked())
    {
        //追溯码查询模式

        if(code.length() == 20 )
        {
            sq = " select bar.oper_date 使用日期 , bar.bar_code_count 用码数量 , "
                 " reg.card_no 病志号, reg.name 患者姓名, bar.clinic_code"
                 " from pha_sto_barcode_rec bar"
                 " left join fin_opr_register reg on reg.clinic_code = bar.clinic_code"
                 " where bar.bar_code = '%1' and valid_state = '1' "
                 " order by bar.oper_date";
            sq = sq.arg(code);

            qDebug()<<"查询指定追溯码的使用记录";
            qDebug()<<sq;

            md_recipe_content->setQuery(sq, pub::db_o);

            if(md_recipe_content->rowCount() < 1)
            {
                snd_error.play();
                QMessageBox::information(this, "注意", "找不到此追溯码的使用记录！");
            }
            else
            {
                int w = ui->tv_recipe_content->width();
                ui->tv_recipe_content->setModel(md_recipe_content);
                pub::setColumnWidth(ui->tv_recipe_content, "0.3^0.2^0.2^0.2^0^0^0^0",w);
            }
        }
        else
        {
            snd_error.play();
            QMessageBox::information(this, "注意", "不是有效的药品追溯码！");
        }

        ui->le_code->setFocus();
        ui->le_code->clear();
        return;
    }


    sq = " select drug_code, trade_name, specs, pack_unit, "
         " id_code, id_code_count "
         " from pha_com_baseinfo "
         " where valid_state = '1' and id_code = '" + base_code + "'";
    qDebug()<<"根据药品识别码查找药品信息："<<sq;
    qro->exec(sq);

    if(qro->next())
    {
        drug_info.clear();
        drug_info["item_code"] = qro->value("drug_code").toString();
        drug_info["trade_name"] = qro->value("trade_name").toString();
        drug_info["specs"] = qro->value("specs").toString();
        drug_info["pack_unit"] = qro->value("pack_unit").toString();
        drug_info["id_code"] = qro->value("id_code").toString();    //药品识别码
        drug_info["id_code_count"] =qro->value("id_code_count").toString(); //追溯码最大可使用次数
        //drug_info["qty"] = "1";
        drug_info["code"] = code;      //扫描到的药品码
        drug_info["base_code"] = base_code; //扫描药品码中提取出来的药品识别码

    }
    else
    {
        snd_error.play();
        QMessageBox::information(this, "注意", "输入的药品识别码无效！");
        ui->le_code->setFocus();
        ui->le_code->clear();
        return;
    }

    current_status = "item_code_return";
    on_pb_item_add_clicked();


}

void tj_form_recipe_check::on_pb_item_add_clicked()
{

    qDebug()<<"\n\non_pb_item_add_clicked， 增加条码至临时表。开始。。。 \n";

    QString tmp_sq;

    if(drug_info.isEmpty())
    {
        QMessageBox::critical(this, "注意", "未指定药品项目！");
        ui->le_code->setFocus();
        ui->le_code->clear();
        qDebug()<<"on_pb_item_add_clicked， 未指定药品项目。 \n";
        return;
    }

    int item_qty = 0;//药品应调配数量
    int item_counted = 0;//本次已经调配的数量
    int id_count_scaned_old = 0; //历史数量
    int id_count_scaned_this = 0; //本处方数量

    qDebug()<<"提取已经调配数量 "<<drug_info["item_code"]<<"\n";
    tmp_sq = "select qty_r, qty_w from tmp_recipe_check "; //
    tmp_sq += " where item_code = '" + drug_info["item_code"] + "' ";
    qDebug()<<tmp_sq<<"\n";

    qrmt->exec(tmp_sq);

    if(qrmt->next())
    {
        item_qty = qrmt->value(0).toInt();
        item_counted = qrmt->value(1).toInt();

        if(item_qty == item_counted)
        {
            snd_error.play();
            QMessageBox::information(this, "注意", "当前药品调配数量已经完成！");
            ui->le_code->setFocus();
            ui->le_code->clear();

            qDebug()<<"on_pb_item_add_clicked， 当前药品调配数量已经完成。\n";

            return;

        }

    }
    else
    {
        snd_error.play();
        QMessageBox::critical(this, "注意", "扫描录入的药品信息与处方信息不匹配！");
        ui->le_code->setFocus();
        ui->le_code->clear();

        qDebug()<<"on_pb_item_add_clicked， 扫描录入的药品信息与处方信息不匹配。\n";

        return;
    }

    if(drug_info["id_code_count"].toInt() > 0 && !is_repair)
    {
        qDebug()<<"有追溯码的药品，非补录状态，进行数量检查。\n";
        qDebug()<<"提取历史数据\n";
        sq = "select sum(bar_code_count) "
             " from pha_sto_barcode_rec "
             " where "
             " bar_code = '"
                + drug_info["code"]
                + "' and valid_state = '1' ";
        qDebug()<<sq<<"\n";

        if(!qro->exec(sq))
        {
            QMessageBox::critical(this, "注意", "提取历史数据失败！");
            qDebug()<<"on_pb_item_add_clicked， 提取历史数据失败。 \n";
            return;
        }

        qro->next();

        id_count_scaned_old = qro->value(0).toInt();
        qDebug()<<"历史数据 : "<<QString::number(id_count_scaned_old)<<"\n";
        qDebug()<<"检查当前条码在本处方中是否已经扫描\n";
        tmp_sq = "select bar_code_count from tmp_recipe_code_list "; //
        tmp_sq += " where bar_code = '" + drug_info["code"] + "' ";
        qDebug()<<tmp_sq<<"\n";

        qrmt->exec(tmp_sq);

        if(qrmt->next())
        {
            snd_error.play();
            QMessageBox::information(this, "注意", "条码已经使用！");
            ui->le_code->setFocus();
            ui->le_code->clear();
            qDebug()<<"on_pb_item_add_clicked， 当前条码在本处方中已经扫描。\n";

            return;

        }

        //检查码累计数量是否超限，历史数量 >= 码空间数量
        if( id_count_scaned_old >= drug_info["id_code_count"].toInt() )
        {
            snd_error.play();
            QMessageBox::information(this, "注意", "条码使用次数超限！");
            ui->le_code->setFocus();
            ui->le_code->clear();

            qDebug()<<"on_pb_item_add_clicked， 条码使用次数超限。\n";

            return;
        }

        //可用数量 = 码空间数量 - 已经使用数量
        id_count_scaned_this = drug_info["id_code_count"].toInt() - id_count_scaned_old;

        if(id_count_scaned_this > (item_qty - item_counted))
        {
            qDebug()<<"码空间数量大于需要数量\n";
            id_count_scaned_this = item_qty - item_counted;
        }

        qDebug()<<"本次扫描有效数量 : "<< QString::number(id_count_scaned_this)<<"\n";

    }
    else
    {
        //无追溯码药品，每次扫描 数量 + 1
        id_count_scaned_this = 1;
    }

    QString code_scaned = ui->le_code->text().trimmed();
    QString add_mode;


    qDebug()<<"保存 tmp_recipe_check 临时表";
    sq = " update tmp_recipe_check set ";

    if(ui->le_count->text().isEmpty())
    {
        //扫码增加药品
        sq += " qty_w = qty_w + " + QString::number(id_count_scaned_this) + "," ;
        add_mode = "scan";
    }
    else
    {
        //补录修改数量
        sq += " qty_w = " + ui->le_count->text() + "," ;
        add_mode = "append";
    }

    sq += " bar_code_base = '" + drug_info["base_code"] + "',";   //溯源码包含的药品识别码
    sq += " bar_code = '" + drug_info["code"] + "'";   //溯源码包含的药品识别码
    sq += " where "
          " item_code = '" + drug_info["item_code"] + "'";
    // and qty_r > qty_w

    qDebug()<<"变更窗口药品数量："<<sq<<"\n";
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "保存药品信息失败！\n" + qrm->lastError().text());

        qDebug()<<"on_pb_item_add_clicked， 保存药品信息失败。\n";

        return;
    }

    //保存扫描过的条码
    sq = "replace into tmp_recipe_code_list ("
         "item_code, bar_code,bar_code_base, bar_code_count, rec_sn " //
         " )values( ";
    sq += "'" + drug_info["item_code"] + "',";
    sq += "'" + drug_info["code"] + "',"; //code_scaned
    sq += "'" + drug_info["base_code"] + "',";
    sq += QString::number(id_count_scaned_this) +",";
    sq += "(select rec_sn from tmp_recipe_check where item_code = '"
            + drug_info["item_code"] + "')";
    sq += ")";

    qDebug()<<"保存扫描过的条码："<<sq<<"\n";

    if(!qrm->exec(sq))
    {
        QMessageBox::information(this, "注意", "保存条码信息失败！\n" + qrm->lastError().text());

        qDebug()<<"on_pb_item_add_clicked， 保存条码信息失败。\n";

        return;
    }

    ui->le_code->setFocus();
    ui->le_code->clear();

    ui->le_count->clear();
    ui->le_item_name->clear();

    sq = "select item_name 药品名称, specs 规格, qty_unit 单位, qty_r 处方数量,qty_w 投放数量,"//0-4
         " item_code, bar_code "//5-6
         " from tmp_recipe_check order by sequence_no";

    md_recipe_content->setQuery(sq, pub::db_m);

    ui->tv_recipe_content->setModel(md_recipe_content);
    int w = ui->tv_recipe_content->width();
    pub::setColumnWidth(ui->tv_recipe_content, "0.35^0.2^0.1^0.13^0.13", w);

    recipe_compare();
    drug_info.clear();
    if(recipe_finished)
    {
        QMessageBox::StandardButton bt;
        bt = QMessageBox::question(this, "注意", "处方匹配完成，是否保存？");
        if(bt == QMessageBox::Yes)
        {
            on_pb_save_clicked();
        }
        else
        {
            ui->pb_save->setFocus();
        }
    }

    qDebug()<<"\n\non_pb_item_add_clicked， 结束。\n";
}

void tj_form_recipe_check::recipe_compare()
{
    sq = "select * from tmp_recipe_check where qty_r <> qty_w";
    qrm->exec(sq);
    if(qrm->next())
    {
        //有未完成项目
        ui->le_code->clear();
        ui->le_code->setFocus();
    }
    else
    {
        //全部项目已经匹配
        snd_drug_finish.play();
        recipe_finished = true;
    }

}

void tj_form_recipe_check::on_pb_fresh_recipe_clicked()
{

    if(pub::send_oper_code.isEmpty() || pub::druged_oper_code.isEmpty())
    {
        QMessageBox::information(this, "注意", "请在付药窗口设置正确的药师信息！");
        return;
    }

    ui->rb_drug_check->setChecked(true);

    QString reg_date = ui->de_recipe_date->date().toString("yyyy-MM-dd");

    //清空旧数据
    qrm->exec("delete from tmp_recipe_code_list");
    qrm->exec("delete from tmp_recipe_check");

    sq = "select distinct pr.recipe_no 处方号, REG.name 患者姓名, PR.CLINIC_CODE, "
         " PR.CARD_NO, PR.INVOICE_NO"
         " from SUN_RECIPE_PR pr"
         " LEFT JOIN FIN_OPB_FEEDETAIL fee on fee.recipe_no = PR.recipe_no "
         " LEFT JOIN FIN_OPR_REGISTER reg on reg.CLINIC_CODE = PR.CLINIC_CODE "
         " and reg.reg_date > to_date('%1', 'yyyy-mm-dd') "
         " where PR.OPER_DATE > to_date('%1', 'yyyy-mm-dd') "
         " and pr.ANALYZED = '0' and pr.print_flag = '1' "
         " and fee.cancel_flag = '1' "; //
    sq = sq.arg(reg_date);

    qDebug()<<"提取未校对处方号："<<sq;

    md_recipe_list->setQuery(sq, pub::db_o);

    ui->tv_recipe_list->setModel(md_recipe_list);
    int w = ui->tv_recipe_list->width();
    pub::setColumnWidth(ui->tv_recipe_list, "0.4^0.4", w);

    ui->le_code->setFocus();
    ui->le_code->clear();
    ui->le_count->clear();
    ui->le_item_name->clear();
    ui->le_recipe_no->clear();
    ui->ck_manual->setChecked(false); //手工录入追溯码
    cur_recipe_no.clear();
    md_recipe_content->setQuery(NULL);
    ui->le_recipe_no->setFocus();

    qDebug()<<"cur_clinic_code"<<cur_clinic_code<<"\n";

    //检查患者是否还有未审核的处方
    qro->exec(sq);
    while(qro->next())
    {
        QString card_no = qro->value(3).toString();

        if( cur_card_no == card_no)
        {
            ui->rb_drug_check->setChecked(true);

            QString rec_no = qro->value(0).toString();

            current_status = "recipe_list_clicked";
            ui->le_recipe_no->setText(rec_no);

            on_le_recipe_no_returnPressed();
            return;
        }
    }

    cur_card_no.clear();
    cur_clinic_code.clear();
}

void tj_form_recipe_check::on_pb_exit_clicked()
{
    close();
}

void tj_form_recipe_check::on_tv_recipe_list_clicked(const QModelIndex &index)
{

    ui->rb_drug_check->setChecked(true);

    QString rec_no = index.siblingAtColumn(0).data().toString();

    sq = "select recipe_state from pha_sto_recipe"
         " where recipe_no = '" + rec_no + "'";
    qDebug()<<"调配前确认处方状态是否有效："<<sq<<"\n";
    qro->exec(sq);
    qro->next();

    if(qro->value(0).toString() == "3" //已发药
            ||qro->value(0).toString() == "5"//已退费
            )
    {
        QMessageBox::information(this, "注意", "处方状态无效，请刷新处方列表！");
        return;
    }

    current_status = "recipe_list_clicked";
    ui->le_recipe_no->setText(rec_no);

    on_le_recipe_no_returnPressed();
}

void tj_form_recipe_check::on_tv_recipe_list_doubleClicked(const QModelIndex &index)
{
    on_tv_recipe_list_clicked(index);
}


void tj_form_recipe_check::on_tv_recipe_content_clicked(const QModelIndex &index)
{

    if(ui->rb_code_check->isChecked() || ui->rb_code_repair->isChecked())
    {
        return;
    }

    current_status = "recipe_content_clicked";
    int w = index.siblingAtColumn(4).data().toInt();//已扫码数量
    int r = index.siblingAtColumn(3).data().toInt();//处方数量
    QString drug_code = index.siblingAtColumn(5).data().toString();//药品编码

    //检索药品基础信息
    sq = "select drug_code, trade_name, specs, pack_unit, id_code, id_code_count"
         " from pha_com_baseinfo where drug_code = '" + drug_code + "'";
    qDebug()<<"根据药品编码查找药品信息："<<sq;
    qro->exec(sq);

    if(qro->next())
    {
        drug_info.clear();
        drug_info["item_code"] = qro->value("drug_code").toString();
        drug_info["trade_name"] = qro->value("trade_name").toString();
        drug_info["specs"] = qro->value("specs").toString();
        drug_info["pack_unit"] = qro->value("pack_unit").toString();
        drug_info["id_code"] = qro->value("id_code").toString();    //识别码
        drug_info["id_code_count"] = qro->value("id_code_count").toString();
        drug_info["code"] = index.siblingAtColumn(6).data().toString();//扫描到的编码
        drug_info["base_code"] = drug_info["id_code"];  //进入补录数据流程，不需要再次核对品种

    }
    else
    {
        QMessageBox::information(this, "注意", "列表中的药品编码无效！");
        qDebug()<<"on_tv_recipe_content_clicked, 列表中的药品编码无效\n";
        current_status = "";
        return;
    }

    //窗口数量是否达到处方数量
    if(w < r)
    {

        if(w > 0)
        {
            //窗口数量大于 0 ，说明有过扫码录入
            ui->le_item_name->setText(index.siblingAtColumn(0).data().toString());
            ui->le_count->setText(index.siblingAtColumn(3).data().toString());
            ui->le_code->setText(index.siblingAtColumn(6).data().toString());
            ui->le_count->setFocus();
        }
        else
        {
            //窗口数量为 0 ，无编码直接录入
            if(drug_info["id_code_count"].toInt() > 0)
            {
                QMessageBox::information(this, "注意", "有追溯码的药品不允许进行无编码录入！");
                drug_info.clear();
                ui->le_code->setFocus();
                ui->le_code->clear();
                ui->le_count->clear();
                return;
            }
            QMessageBox::StandardButton bt;
            bt = QMessageBox::question(this, "注意", "未扫描药品码，确认进行无编码录入？");
            if(bt == QMessageBox::Yes)
            {
                ui->le_item_name->setText(index.siblingAtColumn(0).data().toString());
                ui->le_count->setText(index.siblingAtColumn(3).data().toString());
                ui->le_code->setText("no_code");
                drug_info["code"] = "no_code";
                if(drug_info["base_code"].isEmpty())
                {
                    drug_info["base_code"] = "no_code";
                }
                drug_info["id_code_count"] = "0";

                on_pb_item_add_clicked();
            }
            else
            {
                ui->le_code->setFocus();
                ui->le_code->clear();
            }
        }
    }
    current_status = "";
}

void tj_form_recipe_check::on_tv_recipe_content_doubleClicked(const QModelIndex &index)
{
    on_tv_recipe_content_clicked(index);
}

void tj_form_recipe_check::on_pb_save_clicked()
{
    if(!recipe_finished)
    {
        snd_error.play();
        QMessageBox::information(this, "注意", "处方尚未完成！");
        ui->le_code->setFocus();
        ui->le_code->clear();
        return;
    }
    //保存 recipe_pr 的处方核验标志
    sq = "update sun_recipe_pr set analyzed = '1' , analyzed_date = sysdate"
         " where recipe_no = '" + cur_recipe_no + "'";
    qro->exec(sq);
    if(qro->numRowsAffected() != 1)
    {
        QMessageBox::critical(this, "注意", "保存处方核验失败！");
        ui->le_code->setFocus();
        ui->le_code->clear();
        return;
    }

    //保存 扫描过的条码
    sq = "select * from tmp_recipe_code_list";
    qrm->exec(sq);
    while(qrm->next())
    {
        sq = "insert into pha_sto_barcode_rec("
             " rec_sn, " //等于 fin_opb_feedetail.mo_order 和 met_order_recipedetail.sequence_no';
                "drug_code, "
                "bar_code ,"    //处方中出现过的条码
                "bar_code_base,"  //药品识别码。溯源码前7位，或制剂码，或商品码
                "clinic_code," //clinic_code
                "recipe_no,"    //处方号
                "oper_date,"
                "oper_code,"
                "valid_state,"   //有效标志，1有效，非1无效
                "bar_code_count"    //条码出现的次数
                ") values(";
        sq += qrm->value("rec_sn").toString() + ",";
        sq += "'" + qrm->value("item_code").toString() + "',";    //处方中出现过的条码
        sq += "'" + qrm->value("bar_code").toString() + "',";    //处方中出现过的条码
        sq += "'" + qrm->value("bar_code_base").toString() + "',";  //药品识别码。溯源码前7位，或制剂码，或商品码
        sq += "'" + cur_clinic_code + "',";   //clinic_code
        sq += "'" + cur_recipe_no + "',";      //处方号
        sq += "sysdate,";
        sq += "'" + pub::usr_code + "',";
        sq += "'1',";   //有效标志，1有效，非1无效
        sq += qrm->value("bar_code_count").toString();      //条码出现的次数
        sq += ")";

        qDebug()<<"保存扫描过的条码："<<sq;
        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "注意", "保存条码记录失败！\n" + qro->lastError().text());
            return;
        }

        //可能存在退费追溯码
        sq = "update pha_sto_barcode_return set"
             " use_date = sysdate,"
             " reused = '1'"
             " where bar_code = '"+ qrm->value("bar_code").toString() + "'";    //处方中出现过的条码
        sq += " and valid_status = '1' and reused = '0' ";

        qDebug()<<"保存扫描退费条码："<<sq;
        if(!qro->exec(sq))
        {
            QMessageBox::information(this, "注意", "保存退费条码记录失败！\n" + qro->lastError().text());
            return;
        }

    }

    processData(cur_recipe_no);

    on_pb_fresh_recipe_clicked();
}

void tj_form_recipe_check::on_le_code_textChanged(const QString &arg1)
{
    //qDebug()<<"current status is "<<current_status<<"\n";

    if( current_status == "recipe_content_clicked" || is_repair )
    {
        //处方明细点被击状态，处方补录状态 ,不响应事件
        qDebug()<<"current status is "<<current_status<<"\n";
        return;
    }

    if(arg1.trimmed().isEmpty() || arg1.trimmed().length() > 20)
    {
        qDebug()<<"current status is "<<current_status<<"\n";
        qDebug()<<"追溯码长度无效 : "<<arg1<<"\n";
        ui->le_code->clear();
        ui->le_code->setFocus();

        if(tm_code_input->isActive())
        {
            tm_code_input->stop();
        }
        return;
    }

    if(tm_code_input->isActive())
    {
        tm_code_input->stop();
    }

    tm_code_input->start(200);
}

void tj_form_recipe_check::on_pb_get_ret_code_clicked()
{
    //QModelIndex mdidx = ui->tv_recipe_list->currentIndex();

    if(cur_card_no.isEmpty())
    {
        QMessageBox::information(this, "注意", "未选定有效处方记录！");
        return;
    }

    //QString card_no = mdidx.siblingAtColumn(3).data().toString();

    sq = " select bar_code, drug_code, bar_code_count from PHA_STO_BARCODE_RETURN "
         " where card_no = '%1' and valid_status = '1' "
         " and reused = '0' and scaned = '0'";//未用，未扫描
    sq = sq.arg(cur_card_no);
    qDebug()<<"提取退费追溯码："<<sq<<"\n";
    qro->exec(sq);

    //防止录入追溯码触发事件
    ui->le_code->blockSignals(true);

    while (qro->next())
    {
        sq = " select item_name from tmp_recipe_check"
             " where item_code = '" + qro->value("drug_code").toString() + "'";
        qrm->exec(sq);
        qDebug()<<"检查项目是否出现在当前窗口："<<sq<<"\n";
        if(!qrm->next())
        {
            continue;
        }
        else
        {
            ui->le_code->setText(qro->value("bar_code").toString());
            on_le_code_returnPressed();
        }

        //sq = " select item_name from tmp_recipe_check"
        //     " where qty_r > qty_w and item_code = "
        //     "'" + qro->value("drug_code").toString() + "'";
        //qrm->exec(sq);
        //qDebug()<<"检查项目是否调配完成："<<sq<<"\n";
        //if(!qrm->next())
        //{
            //数量调配完成
            //break;
        //    continue;
        //}
    }
    ui->le_code->blockSignals(false);
}

void tj_form_recipe_check::processData(QString recipe_no)
{
    qDebug()<<"processData recipe_no is "<<recipe_no<<"\n";

    QList<QMap<QString,QString>> applyOutList;  //出库申请
    QList<QMap<QString,QString>> storageList;   //库存数据
    QMap<QString,QString> mp;
    //检索数据是否已经被处理
    qro->prepare("select recipe_no from pha_sto_recipe where  "
                 "RECIPE_STATE = '3' and recipe_no = :recipe_no");
    qro->bindValue(":recipe_no",recipe_no);

    if(!qro->exec())
    {
        QMessageBox::information(this,"error", qro->lastError().text());
        return;
    }
    if(qro->next())
    {
        qDebug()<<"recipe_no : "<< recipe_no << " , related data has been saved.";
        return; //已经做过数据处理
    }

    pub::db_o.transaction();
    QSqlQuery * qro_t1 = new QSqlQuery(pub::db_o);
    //QSqlQuery * qro_t2 = new QSqlQuery(pub::db_o);

    //update pha_sto_recipe 数据
    qro_t1->prepare("update pha_sto_recipe set RECIPE_STATE = '3', DRUGED_QTY = RECIPE_QTY, "
                 "DRUGED_DATE = sysdate, SEND_DATE = sysdate, EXT_FLAG1 = :ext_flag1,"
                 "SEND_OPER = :SEND_OPER, DRUGED_OPER = :DRUGED_OPER "
                 " where recipe_no = :recipe_no");
    qro_t1->bindValue(":ext_flag1", terminalCode);
    qro_t1->bindValue(":SEND_OPER", pub::send_oper_code);
    qro_t1->bindValue(":DRUGED_OPER", pub::druged_oper_code);
    qro_t1->bindValue(":recipe_no", recipe_no);
    qro_t1->exec();

    if(!qro_t1->exec())
    {
        QMessageBox::information(this,"return error", qro_t1->lastError().text());
        delete qro_t1;
        pub::db_o.rollback();
        return;
    }

    //临时保存 PHA_COM_APPLYOUT

    qro_t1->prepare("SELECT * FROM PHA_COM_APPLYOUT WHERE "
                 " RECIPE_NO = :rcptn AND DRUG_DEPT_CODE = :dptcd AND CLASS3_MEANING_CODE = 'M1'"
                 " AND APPLY_STATE = '0' "
                 " order by comb_no,sequence_no");

    qro_t1->bindValue(":dptcd", deptCode);
    qro_t1->bindValue(":rcptn", recipe_no);
    if(!qro_t1->exec())
    {
        QMessageBox::information(this,"error", qro_t1->lastError().text());
        delete qro_t1;
        pub::db_o.rollback();
        return;
    }
    //
    while(qro_t1->next())
    {
        mp["APPLY_NUMBER"] = qro_t1->value("APPLY_NUMBER").toString();//申请流水号
        mp["DEPT_CODE"] = qro_t1->value("DEPT_CODE").toString();//申请部门编码（科室或者病区）
        mp["DRUG_DEPT_CODE"] = qro_t1->value("DRUG_DEPT_CODE").toString();//发药部门编码
        mp["CLASS3_MEANING_CODE"] = qro_t1->value("CLASS3_MEANING_CODE").toString();//出库申请分类
        mp["DRUG_CODE"] = qro_t1->value("DRUG_CODE").toString();//药品编码
        mp["TRADE_NAME"] = qro_t1->value("TRADE_NAME").toString();//药品商品名
        mp["DRUG_TYPE"] = qro_t1->value("DRUG_TYPE").toString();//药品类别
        mp["SPECS"] = qro_t1->value("SPECS").toString();//规格
        mp["PACK_UNIT"] = qro_t1->value("PACK_UNIT").toString();//包装单位
        mp["PACK_QTY"] = qro_t1->value("PACK_QTY").toString();//包装数
        mp["MIN_UNIT"] = qro_t1->value("MIN_UNIT").toString();//最小单位
        mp["RETAIL_PRICE"] = qro_t1->value("RETAIL_PRICE").toString();//零售价
        mp["APPLY_OPERCODE"] = qro_t1->value("APPLY_OPERCODE").toString();//申请人编码
        QDateTime dt = qro_t1->value("APPLY_DATE").toDateTime();
        mp["APPLY_DATE"] = dt.toString("yyyyMMddHHmmss");//申请日期
        mp["APPLY_STATE"] = qro_t1->value("APPLY_STATE").toString();//申请状态 0申请，1核准（出库），2作废，3暂不摆药
        mp["APPLY_NUM"] = qro_t1->value("APPLY_NUM").toString();//申请出库量(每付的总数量)
        mp["PATIENT_ID"] = qro_t1->value("PATIENT_ID").toString();//患者编号
        mp["PATIENT_DEPT"] = qro_t1->value("PATIENT_DEPT").toString();//患者科室
        mp["DRUGED_DEPT"] = qro_t1->value("DRUGED_DEPT").toString();//摆药科室
        mp["DRUGED_EMPL"] = qro_t1->value("DRUGED_EMPL").toString();//摆药人
        dt = qro_t1->value("DRUGED_DATE").toDateTime();
        mp["DRUGED_DATE"] = dt.toString("yyyyMMddHHmmss");//摆药日期
        mp["DOSE_ONCE"] = qro_t1->value("DOSE_ONCE").toString();//每次剂量
        mp["DOSE_UNIT"] = qro_t1->value("DOSE_UNIT").toString();//剂量单位
        mp["USAGE_CODE"] = qro_t1->value("USAGE_CODE").toString();//用法代码
        mp["USE_NAME"] = qro_t1->value("USE_NAME").toString();//用法名称
        mp["DFQ_FREQ"] = qro_t1->value("DFQ_FREQ").toString();//频次代码
        mp["DFQ_CEXP"] = qro_t1->value("DFQ_CEXP").toString();//频次名称
        mp["DOSE_MODEL_CODE"] = qro_t1->value("DOSE_MODEL_CODE").toString();//剂型编码
        mp["MO_ORDER"] = qro_t1->value("MO_ORDER").toString();//医嘱流水号
        mp["COMB_NO"] = qro_t1->value("COMB_NO").toString();//组合序号
        mp["RECIPE_NO"] = qro_t1->value("RECIPE_NO").toString();//处方号
        mp["SEQUENCE_NO"] = qro_t1->value("SEQUENCE_NO").toString();//处方内项目流水号
        mp["VALID_STATE"] = qro_t1->value("VALID_STATE").toString();//有效状态（0有效，1无效，2不摆药）
        applyOutList << mp;
        mp.clear();
    }
    qDebug()<<"applyOutList.length"<<applyOutList.length();

    //update PHA_COM_APPLYOUT
    qro_t1->prepare(" UPDATE PHA_COM_APPLYOUT"
                 " SET APPLY_STATE = '2', DRUGED_DEPT = DRUG_DEPT_CODE, DRUGED_EMPL = :empl,"
                 " DRUGED_DATE = sysdate, DRUGED_NUM = 0, OUT_BILL_CODE = '0' "
                 " WHERE DRUG_DEPT_CODE = :dept AND CLASS3_MEANING_CODE = 'M1' "
                 " AND RECIPE_NO = :rcn");
    qro_t1->bindValue(":dept", deptCode);
    qro_t1->bindValue(":empl", pub::usr_code);
    qro_t1->bindValue(":rcn", recipe_no);
    if(!qro_t1->exec())
    {
        QMessageBox::information(this,"Error in update pha_com_applyout", qro_t1->lastError().text());
        delete qro_t1;
        pub::db_o.rollback();
        return;
    }

    //INSERT pha_com_output
    foreach(mp, applyOutList)
    {
        //查询药品库存表PHA_COM_STORAGE，提取有效库存数据
        qro_t1->prepare("SELECT * FROM PHA_COM_STORAGE WHERE DRUG_DEPT_CODE = :dptcd "
                     " AND store_sum > 0 and DRUG_CODE = :drcd AND Valid_Flag = '1' "
                     //东软应用使用效期优先， 本应用使用group_code + batch_no。
                     " Order by to_number(group_code),VALID_DATE ");
        qro_t1->bindValue(":dptcd", deptCode);
        qro_t1->bindValue(":drcd", mp["DRUG_CODE"]);
        if(!qro_t1->exec()){
            QMessageBox::information(this,"error", qro_t1->lastError().text());
            delete qro_t1;
            pub::db_o.rollback();
            return;
        }

        while(qro_t1->next())
        {
            QMap<QString, QString> m;
            m["DRUG_DEPT_CODE"] = qro_t1->value("DRUG_DEPT_CODE").toString();//库存科室 0-全部部门
            m["DRUG_CODE"] = qro_t1->value("DRUG_CODE").toString();//药品编码
            m["GROUP_CODE"] = qro_t1->value("GROUP_CODE").toString();//批次号
            m["BATCH_NO"] = qro_t1->value("BATCH_NO").toString();//批号
            m["TRADE_NAME"] = qro_t1->value("TRADE_NAME").toString();//药品商品名
            m["SPECS"] = qro_t1->value("SPECS").toString();//规格
            m["DRUG_TYPE"] = qro_t1->value("DRUG_TYPE").toString();//药品类别
            m["DRUG_QUALITY"] = qro_t1->value("DRUG_QUALITY").toString();//药品性质
            m["RETAIL_PRICE"] = qro_t1->value("RETAIL_PRICE").toString();//零售价
            m["WHOLESALE_PRICE"] = qro_t1->value("WHOLESALE_PRICE").toString();//批发价
            m["PURCHASE_PRICE"] = qro_t1->value("PURCHASE_PRICE").toString();//实进价
            m["PACK_UNIT"] = qro_t1->value("PACK_UNIT").toString();//包装单位
            m["PACK_QTY"] = qro_t1->value("PACK_QTY").toString();//包装数
            m["MIN_UNIT"] = qro_t1->value("MIN_UNIT").toString();//最小单位
            m["SHOW_FLAG"] = qro_t1->value("SHOW_FLAG").toString();//显示的单位标记
            QDateTime dt = qro_t1->value("VALID_DATE").toDateTime();
            m["VALID_DATE"] = dt.toString("yyyyMMddHHmmss");//有效期
            m["STORE_SUM"] = qro_t1->value("STORE_SUM").toString();//库存数量
            m["STORE_COST"] = qro_t1->value("STORE_COST").toString();//库存金额
            m["PREOUT_SUM"] = qro_t1->value("PREOUT_SUM").toString();//预扣库存数量
            m["PREOUT_COST"] = qro_t1->value("PREOUT_COST").toString();//预扣库存金额
            m["VALID_FLAG"] = qro_t1->value("VALID_FLAG").toString();//有效性标志 0 在用 1 停用 2 废弃
            m["PRODUCER_CODE"] = qro_t1->value("PRODUCER_CODE").toString();//生产厂家
            m["LAST_MONTH_NUM"] = qro_t1->value("LAST_MONTH_NUM").toString();//最近一次月结的库存量
            m["PLACE_CODE"] = qro_t1->value("PLACE_CODE").toString();//货位号
            m["STATE"] = qro_t1->value("STATE").toString();//在库状态（0-暂入库，1正式入库）
            m["MARK"] = qro_t1->value("MARK").toString();//备注
            m["OPER_CODE"] = qro_t1->value("OPER_CODE").toString();//操作员
            m["OPER_DATE"] = qro_t1->value("OPER_DATE").toString();//操作日期
            m["INVOICE_NO"] = qro_t1->value("INVOICE_NO").toString();//发票号
            m["ARK_FLAG"] = qro_t1->value("ARK_FLAG").toString();//'是否药柜管理药品 1 药柜管理 0 非药柜管理';
            m["ARK_QTY"] = qro_t1->value("ARK_QTY").toString();//药柜管理库存汇总数量
            m["manu_date"] = qro_t1->value("manu_date").toDate().toString("yyyy-MM-dd");//生产日期
            storageList << m;
        }

        //处理库存数据消耗
        QMap<QString,QString> sto;
        int aplNum = mp["APPLY_NUM"].toInt();   //申请出库数量
        int opNum;                              //本批次出库数量
        foreach(sto ,storageList)
        {
            int stoNum = sto["STORE_SUM"].toInt();  //本批次库存数量

            if(aplNum <= stoNum)
            {       //库存数量允许出库
                opNum = aplNum;     //出库数量 = 申请数量
            }
            else
            {                      //申请数量大于库存数量
                opNum = stoNum;     //出库数量 = 库存数量
            }
            qro_t1->exec("select SEQ_PHA_OUTBILL_ID.NEXTVAL from dual");
            qro_t1->next();
            QString OUT_BILL_CODE = qro_t1->value(0).toString();

            qro_t1->prepare("INSERT INTO pha_com_output (manu_date, DRUG_DEPT_CODE ,OUT_BILL_CODE ,SERIAL_CODE ,"
                         "GROUP_CODE , OUT_LIST_CODE ,OUT_TYPE ,CLASS3_MEANING_CODE ,IN_BILL_CODE ,"
                         "IN_SERIAL_CODE ,IN_LIST_CODE ,DRUG_CODE , TRADE_NAME ,DRUG_TYPE ,"
                         "DRUG_QUALITY ,SPECS ,PACK_UNIT ,PACK_QTY ,MIN_UNIT ,SHOW_FLAG , "
                         "SHOW_UNIT ,BATCH_NO , VALID_DATE , PRODUCER_CODE ,COMPANY_CODE ,"
                         "RETAIL_PRICE ,WHOLESALE_PRICE ,PURCHASE_PRICE , OUT_NUM ,SALE_COST ,"
                         "TRADE_COST ,APPROVE_COST ,STORE_NUM , STORE_COST ,SPECIAL_FLAG ,"
                         "OUT_STATE ,APPLY_NUM ,APPLY_OPERCODE ,APPLY_DATE ,EXAM_NUM ,EXAM_OPERCODE ,"
                         "EXAM_DATE ,APPROVE_OPERCODE ,APPROVE_DATE ,PLACE_CODE ,RETURN_NUM ,"
                         "DRUGED_BILL ,MED_ID ,DRUG_STORAGE_CODE , RECIPE_NO ,SEQUENCE_NO ,"
                         "GET_PERSON ,MARK ,OPER_CODE , OPER_DATE,ARK_FLAG,ARK_BILL_CODE,OUT_DATE"
                         ") VALUES ("
                         ":manu_date, :DRUG_DEPT_CODE ,:OUT_BILL_CODE ,1 ,:GROUP_CODE , '' ,'M1' ,'M1' ,0 ,0 ,'',"
                         ":DRUG_CODE , :TRADE_NAME ,:DRUG_TYPE ,:DRUG_QUALITY ,:SPECS ,:PACK_UNIT ,"
                         ":PACK_QTY ,:MIN_UNIT ,'0' , '' ,:BATCH_NO , :VALID_DATE ,:PRODUCER_CODE ,"
                         "(select  t.company_code from pha_com_input t where t.drug_dept_code = :DRUG_DEPT_CODE"
                         " and t.drug_code = :DRUG_CODE and t.group_code = :GROUP_CODE and rownum  = 1),"
                         ":RETAIL_PRICE ,0 ,:PURCHASE_PRICE , :OUT_NUM ,"
                         "(:OUT_NUM/:PACK_QTY)*:RETAIL_PRICE ,0 ,(:OUT_NUM/:PACK_QTY)*:PURCHASE_PRICE,"
                         ":STORE_NUM ,0 ,'0' ,'2' ,0 "
                         ",:APPLY_OPERCODE , SYSDATE ,:EXAM_NUM ,:EXAM_OPERCODE ,SYSDATE ,'' , SYSDATE ,"
                         "'' ,0 ,'0' ,'' ,:DRUG_STORAGE_CODE , :RECIPE_NO ,:SEQUENCE_NO ,:GET_PERSON ,"
                         "'' ,:OPER_CODE ,SYSDATE,'0',0,SYSDATE )");

            qro_t1->bindValue(":DRUG_DEPT_CODE", deptCode);//出库科室编码
            qro_t1->bindValue(":OUT_BILL_CODE",OUT_BILL_CODE);
            qro_t1->bindValue(":GROUP_CODE", sto["GROUP_CODE"]);//批次号
            QDateTime dt = QDateTime::fromString(sto["manu_date"], "yyyy-MM-dd");
            qro_t1->bindValue(":manu_date", dt);//生产日期
            qro_t1->bindValue(":DRUG_CODE", sto["DRUG_CODE"]);//药品编码
            qro_t1->bindValue(":TRADE_NAME", sto["TRADE_NAME"]);//药品商品名
            qro_t1->bindValue(":DRUG_TYPE", sto["DRUG_TYPE"]);//药品类别
            qro_t1->bindValue(":DRUG_QUALITY", sto["DRUG_QUALITY"]);//药品性质
            qro_t1->bindValue(":SPECS", sto["SPECS"]);//规格
            qro_t1->bindValue(":PACK_UNIT", sto["PACK_UNIT"]);//包装单位
            qro_t1->bindValue(":PACK_QTY", sto["PACK_QTY"]);//包装数
            qro_t1->bindValue(":MIN_UNIT", sto["MIN_UNIT"]);//最小单位
            qro_t1->bindValue(":BATCH_NO", sto["BATCH_NO"]);//批号
            dt = QDateTime::fromString(sto["VALID_DATE"],"yyyyMMddhhmmss");
            qro_t1->bindValue(":VALID_DATE", dt);//有效期
            qro_t1->bindValue(":PRODUCER_CODE", sto["PRODUCER_CODE"]);//生产厂家
            //qro_t1->bindValue(":COMPANY_CODE", sto["COMPANY_CODE"]);//供货单位代码
            qro_t1->bindValue(":RETAIL_PRICE", sto["RETAIL_PRICE"]);//零售价
            //qro_t1->bindValue(":WHOLESALE_PRICE", sto["WHOLESALE_PRICE"]);//批发价
            qro_t1->bindValue(":PURCHASE_PRICE", sto["PURCHASE_PRICE"]);//购入价
            qro_t1->bindValue(":OUT_NUM", opNum);//出库数量
            //qro_t1->bindValue(":SALE_COST","SALE_COST");//零售金额
            //qro_t1->bindValue(":APPROVE_COST",":APPROVE_COST");//购入金额
            qro_t1->bindValue(":STORE_NUM", stoNum - opNum);//出库后库存数量
            //qro_t1->bindValue(":STORE_COST",":STORE_COST");//出库后库存总金额
            qro_t1->bindValue(":APPLY_OPERCODE", mp["APPLY_OPERCODE"]);//申请出库人
            qro_t1->bindValue(":EXAM_NUM", opNum);//审批数量
            qro_t1->bindValue(":EXAM_OPERCODE", pub::usr_code);//审批人
            qro_t1->bindValue(":DRUG_STORAGE_CODE",mp["DEPT_CODE"]);//领药单位编码
            qro_t1->bindValue(":RECIPE_NO", mp["RECIPE_NO"]);//处方号
            qro_t1->bindValue(":SEQUENCE_NO", mp["SEQUENCE_NO"]);//处方流水号
            qro_t1->bindValue(":GET_PERSON",mp["PATIENT_ID"]);//领药人,  clinic_code
            qro_t1->bindValue(":OPER_CODE", pub::usr_code);//操作员
            if(!qro_t1->exec())
            {
                QMessageBox::information(this,"error", qro_t1->lastError().text());
                qDebug()<<"insert pha_com_output error."<<qro_t1->lastQuery();
                delete qro_t1;
                pub::db_o.rollback();
                return;
            }
            //核减库存
            qro_t1->prepare("UPDATE PHA_COM_STORAGE SET STORE_SUM = STORE_SUM - :out_num,"
                         "STORE_COST = STORE_COST - :out_num / pack_qty * RETAIL_PRICE, "
                         "BILL_CODE = :bill_code, SERIAL_CODE = 0, TARGET_DEPT = :target_dept, "
                         "CLASS2_CODE = '0320|M1', OPER_CODE   = :oper_code, OPER_DATE   = SYSDATE"
                         " WHERE  "
                         " DRUG_DEPT_CODE = :drug_dept_code "
                         " AND DRUG_CODE  = :drug_code"
                         " AND GROUP_CODE = :group_code "
                         " and batch_no = :batch_no");
            qro_t1->bindValue(":out_num", opNum);
            qro_t1->bindValue(":bill_code", OUT_BILL_CODE);
            qro_t1->bindValue(":target_dept" ,mp["DEPT_CODE"]);
            qro_t1->bindValue(":oper_code", pub::usr_code);
            qro_t1->bindValue(":drug_dept_code", deptCode);
            qro_t1->bindValue(":drug_code", sto["DRUG_CODE"]);
            qro_t1->bindValue(":group_code", sto["GROUP_CODE"]);
            qro_t1->bindValue(":batch_no", sto["BATCH_NO"]);

            if(!qro_t1->exec())
            {
                QMessageBox::information(this,"error", qro_t1->lastError().text());
                qDebug()<<"update pha_com_storage error."<<qro_t1->lastQuery();
                delete qro_t1;
                pub::db_o.rollback();
                return;
            }

            //update fin_opb_feedetail
            qro_t1->prepare("update fin_opb_feedetail set CONFIRM_FLAG = '1',"
                         " CONFIRM_CODE = :CONFIRM_CODE, CONFIRM_DEPT = :CONFIRM_DEPT, CONFIRM_DATE = sysdate, "
                         " NOBACK_NUM = 0, CONFIRM_NUM = QTY"
                         " where RECIPE_NO = :RECIPE_NO and MO_ORDER = :MO_ORDER and cancel_flag = '1'");
            qro_t1->bindValue(":CONFIRM_CODE", pub::usr_code);
            qro_t1->bindValue(":CONFIRM_DEPT", deptCode);
            qro_t1->bindValue(":RECIPE_NO", mp["RECIPE_NO"]);
            qro_t1->bindValue(":MO_ORDER", mp["MO_ORDER"]);
            if(!qro_t1->exec()){
                QMessageBox::information(this,"error", qro_t1->lastError().text());
                qDebug()<<"update fin_opb_feedetail error "<<qro_t1->lastError().text();
                qDebug()<<qro_t1->lastQuery();
                qDebug()<<pub::usr_code<<deptCode<<mp["RECIPE_NO"]<<mp["MO_ORDER"];
                delete qro_t1;
                pub::db_o.rollback();
                return;
            }

            aplNum = aplNum - opNum;    //申请数量 = 申请数量 - 已完成数量
            if(aplNum == 0){    //申请数量已经完成，退出循环
                break;
            }
        }
        storageList.clear();
    }
    delete qro_t1;
    //pub::db_o.rollback();
    pub::db_o.commit();
}

